//
//  iPhoneSession.m
//  SCRAP_ObjC
//
//  Created by Capstone Design Fall 2010 on 11/14/10.
//  Copyright 2010 Thunderwear. All rights reserved.
//

#import "iPhoneSession.h"
#import "CardData.h"

// GameKit Session ID for app
#define SCRAPSessionID @"bluetooth3"

@implementation iPhoneSession

@synthesize gameDelegate, gamePeerId, GameOver, playerName;

- (id)init
{	
    if(self=[super init]){
		size = [[CCDirector sharedDirector] winSize];
		gamePeerId = nil;
		GameOver = false;
	}
	
    return self;	
}

- (void)invalidateSession {
	if(gameSession != nil) {
		[gameSession disconnectFromAllPeers]; 
		gameSession.available = NO; 
		[gameSession setDataReceiveHandler: nil withContext: NULL]; 
		gameSession.delegate = nil;
		gamePeerId = nil;
	}
}

-(void)startPicker{
	GKSession *session = [[GKSession alloc] initWithSessionID:SCRAPSessionID displayName:playerName sessionMode:GKSessionModeClient];
	session.delegate = self;
	//session.disconnectTimeout = 100;
	[session setDataReceiveHandler:self withContext:nil];
	session.available = YES;
}

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state { 
	switch (state)
	{
		case GKPeerStateConnected:
			[gameDelegate session:self stopAnimation:YES];
			break;
		case GKPeerStateDisconnected:
			if (peerID == gamePeerId && !GameOver) {
				UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Disconnected" message:[NSString stringWithFormat:@"You were disconnected....reconnect?"] delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
				[alertView show];
				[alertView autorelease];
			}
			break;
		case GKPeerStateAvailable:
				gameSession = session;
				gamePeerId = peerID;
				NSString *newPeerId = [gameSession displayNameForPeer:peerID];
				UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Server Available!" message:[NSString stringWithFormat:@"The Server %@ is Available, Would you like to Connect?", newPeerId] delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
				[alertView show];
				[alertView autorelease];
			break;
		default:
			break;
			
	}
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 1){
		[gameSession connectToPeer:gamePeerId withTimeout:100];
	}
}
- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error{
	NSLog(@"Connection Error: %i",error);
}

- (NSString *) displayNameForPeer:(NSString *)peerID
{	
    return [gameSession displayNameForPeer:peerID];	
}

-(void) updateReserveCount:(int) cnt
{
	NSString *msg = [NSString stringWithFormat:@"RCount %i",cnt];
	NSData* aData;
	aData = [msg dataUsingEncoding: NSASCIIStringEncoding];
	if (gamePeerId != nil) {
		NSArray *array = [NSArray arrayWithObject:gamePeerId];
		[gameSession sendData:aData toPeers:array withDataMode:GKSendDataReliable error:nil];
	}
}

- (void) sendCard:(Card*) x
{
	NSMutableString* c = [NSMutableString stringWithString:@""];
	NSString* xrank = [NSString stringWithFormat:@"%i", x.rank];
	[c appendString: xrank];
	[c appendString: @" "];
	[c appendString: [NSString stringWithFormat: @"%c", x.suit]];
	NSData* aData;
	aData = [c dataUsingEncoding: NSASCIIStringEncoding];
	if (gamePeerId != nil) {
		NSArray *array = [NSArray arrayWithObject:gamePeerId];
		[gameSession sendData:aData toPeers:array withDataMode:GKSendDataReliable error:nil];
	}
	//else [gameSession sendDataToAllPeers:aData withDataMode:GKSendDataReliable error:nil];
}

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
    // Read the bytes in data and perform an application-specific action.
	NSString* aStr;
	aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	NSLog(@"Received Data from %@, %@",peer,aStr);
	[gameDelegate session:self didReceiveMessage:aStr];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

-(void) dealloc
{
	[super dealloc];
}

@end
